# _*_coding:utf-8_*_
import configparser as ConfigParser
import traceback
from . import DmConstant
import os
from ATS.util import constant


class t_table(object):
    def __init__(self, name, columns):
        self.name = name
        self.columns = columns


config_file = DmConstant.DB_CONFIG_FILE
c_file = os.path.join(constant.RCF_PATH, config_file)
config = ConfigParser.RawConfigParser()
config.read(c_file)


def get_table_sequence():
    return get_setting_value("base_setting", "tables").split(',')


def get_setting_value(section, item):
    try:
        return config.get(section, item)
    except Exception as e:
        print("exception", e)
        print(traceback.format_exc())
        return None


table_models = []
tables = get_setting_value("base_setting", "tables").split(',')
print(tables)
for tab in tables:
    column_str = get_setting_value(tab, "cloumns")
    if not column_str:
        continue
    column_list = column_str.split(',')
    table_models.append(t_table(tab, column_list))
# print("table_models", table_models)
businesses = []


def parse_business():
    businesses_str = get_setting_value("BUSINESS", "ITEMS")
    result = {}
    if businesses_str:
        busi_list = businesses_str.split(',')
        global businesses
        businesses.extend(busi_list)
        for busi in busi_list:
            model_list = []
            model_dict = {}
            model_str = get_setting_value("BUSINESS", busi)
            if not model_str:
                continue
            model_split = model_str.split(',')
            for mod in model_split:
                col, ty = mod.split(':')
                model_list.append(col)
                model_dict[col] = ty
            result[busi] = (model_list, model_dict)
    return result


businesses_model = parse_business()


def get_table_dict():
    type_ids = get_setting_value("types", "type_ids").split(',')
    type_dict = {}
    for id in type_ids:
        ty = get_setting_value("types", id)
        type_dict[id] = ty

    global tables, constra_str
    #    tables = get_setting_value("base_setting", "tables").split(',')
    table_dict = {}
    for tab in tables:
        defi = get_setting_value("table_def", tab)
        print("defi", defi)
        columns = defi.split(',')
        column_dict = {}
        constra_sql_list = []
        for colu in columns:
            parts = colu.split(DmConstant.CONSTRAINS_START)
            c_def = parts[0]

            n_v_pair = c_def.split(':')
            if len(n_v_pair) != 2:
                print("Error definition for table %s" % tab)
                continue
            if n_v_pair[1] not in type_dict:
                print("Invalid type id: %s" % n_v_pair[1])
                continue
            column_dict[n_v_pair[0]] = type_dict[n_v_pair[1]]

            if len(parts) == 2:
                constra = parts[1]
                constra_list = constra.split(DmConstant.CONSTRA_SPLIT)
                for constra_ele in constra_list:
                    constra_def = constra_ele.split(DmConstant.CONSTRA_TYPE_SPLIT)
                    con_type = constra_def[0]
                    if DmConstant.CONSTRA_FK == con_type:
                        refs = constra_def[1].split(DmConstant.CONSTRA_REF)
                        ref_table = refs[0]
                        ref_col = refs[1]
                        constra_str = "FOREIGN KEY (%s) REFERENCES %s (%s)" % (n_v_pair[0], ref_table, ref_col)
                    elif DmConstant.CONSTRA_UNIQUE == con_type:
                        column_dict[n_v_pair[0]] = "%s %s" % (type_dict[n_v_pair[1]], "UNIQUE")
                        continue
                    constra_sql_list.append(constra_str)

        table_dict[tab] = {DmConstant.COL_DEF: column_dict, DmConstant.CONSTRA_DEF: constra_sql_list}
    return table_dict


def get_model_by(tab_index):
    tab_name = table_models[tab_index].name
    cols = table_models[tab_index].columns
    return tab_name, cols


if __name__ == '__main__':
    a = get_table_dict()
    print('1')
